
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const path = require('path');

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 数据库初始化
const db = new sqlite3.Database('./agriculture.db');

// 创建数据表
db.serialize(() => {
  // 大棚信息表
  db.run(`CREATE TABLE IF NOT EXISTS greenhouses (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    crop_type TEXT NOT NULL,
    location TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  )`);

  // 传感器数据表
  db.run(`CREATE TABLE IF NOT EXISTS sensor_data (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    greenhouse_id INTEGER,
    soil_temperature REAL,
    soil_humidity REAL,
    air_co2 REAL,
    light_intensity REAL,
    recorded_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (greenhouse_id) REFERENCES greenhouses (id)
  )`);

  // 设备控制记录表
  db.run(`CREATE TABLE IF NOT EXISTS device_controls (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    greenhouse_id INTEGER,
    device_type TEXT,
    action TEXT,
    status TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (greenhouse_id) REFERENCES greenhouses (id)
  )`);

  // 阈值配置表
  db.run(`CREATE TABLE IF NOT EXISTS threshold_configs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    greenhouse_id INTEGER,
    crop_type TEXT,
    soil_temp_min REAL,
    soil_temp_max REAL,
    soil_humidity_min REAL,
    soil_humidity_max REAL,
    co2_min REAL,
    co2_max REAL,
    light_min REAL,
    light_max REAL,
    FOREIGN KEY (greenhouse_id) REFERENCES greenhouses (id)
  )`);
});

// 模拟传感器数据生成
function generateSensorData() {
  return {
    soilTemperature: Math.random() * 10 + 20, // 20-30°C
    soilHumidity: Math.random() * 30 + 40,     // 40-70%
    airCo2: Math.random() * 500 + 400,       // 400-900 ppm
    lightIntensity: Math.random() * 5000 + 5000 // 5000-10000 lux
  };
}

// 获取作物默认阈值配置
function getDefaultThresholds(cropType) {
  const thresholds = {
    'tomato': {
      soil_temp_min: 22, soil_temp_max: 28,
      soil_humidity_min: 60, soil_humidity_max: 80,
      co2_min: 400, co2_max: 800,
      light_min: 6000, light_max: 9000
    },
    'cucumber': {
      soil_temp_min: 20, soil_temp_max: 26,
      soil_humidity_min: 65, soil_humidity_max: 85,
      co2_min: 350, co2_max: 750,
      light_min: 5500, light_max: 8500
    },
    'lettuce': {
      soil_temp_min: 18, soil_temp_max: 24,
      soil_humidity_min: 70, soil_humidity_max: 90,
      co2_min: 400, co2_max: 700,
      light_min: 4000, light_max: 7000
    }
  };
  return thresholds[cropType] || thresholds['tomato'];
}

// API路由
// 获取所有大棚
app.get('/api/greenhouses', (req, res) => {
  db.all('SELECT * FROM greenhouses ORDER BY created_at DESC', (err, rows) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json(rows);
  });
});

// 添加大棚
app.post('/api/greenhouses', (req, res) => {
  const { name, crop_type, location } = req.body;
  db.run('INSERT INTO greenhouses (name, crop_type, location) VALUES (?, ?, ?)',
    [name, crop_type, location], function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    
    // 添加默认阈值配置
    const thresholds = getDefaultThresholds(crop_type);
    db.run(`INSERT INTO threshold_configs 
      (greenhouse_id, crop_type, soil_temp_min, soil_temp_max, soil_humidity_min, soil_humidity_max, co2_min, co2_max, light_min, light_max)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [this.lastID, crop_type, ...Object.values(thresholds)]);
    
    res.json({ id: this.lastID, name, crop_type, location });
  });
});

// 获取大棚的传感器数据
app.get('/api/greenhouses/:id/sensor-data', (req, res) => {
  const { id } = req.params;
  const limit = req.query.limit || 50;
  
  db.all('SELECT * FROM sensor_data WHERE greenhouse_id = ? ORDER BY recorded_at DESC LIMIT ?',
    [id, limit], (err, rows) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json(rows);
  });
});

// 获取阈值配置
app.get('/api/greenhouses/:id/thresholds', (req, res) => {
  const { id } = req.params;
  db.get('SELECT * FROM threshold_configs WHERE greenhouse_id = ?', [id], (err, row) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json(row);
  });
});

// 更新阈值配置
app.put('/api/greenhouses/:id/thresholds', (req, res) => {
  const { id } = req.params;
  const thresholds = req.body;
  
  db.run(`UPDATE threshold_configs SET 
    soil_temp_min = ?, soil_temp_max = ?,
    soil_humidity_min = ?, soil_humidity_max = ?,
    co2_min = ?, co2_max = ?,
    light_min = ?, light_max = ?
    WHERE greenhouse_id = ?`,
    [...Object.values(thresholds), id], function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json({ success: true });
  });
});

// 控制设备
app.post('/api/greenhouses/:id/control', (req, res) => {
  const { id } = req.params;
  const { device_type, action } = req.body;
  
  db.run('INSERT INTO device_controls (greenhouse_id, device_type, action, status) VALUES (?, ?, ?, ?)',
    [id, device_type, action, 'completed'], function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    
    // 通过Socket通知前端
    io.emit('deviceControl', {
      greenhouseId: id,
      deviceType: device_type,
      action: